package com.example.dotavideo;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.dotavideo.bean.VideoBean;
import com.example.dotavideo.util.CommonLog;
import com.example.dotavideo.util.LogFactory;

public class VideoPlayActivity extends Activity{
  
  private CommonLog log = LogFactory.createLog();
  
  private final int SHOW_RELATIVE = 1;
  private final int HIDE_RELATIVE = 2;
  private final int SHOW_PROGRESS = 3;
  private final int HIDE_PROGRESS = 4;
  private final int PLAY_SNED_IR_CODE_KEY_TONE = 204;
  private final int PLAY_VIDEO = 5;
  private final int TURN_NEXT_SOURCE = 6;
  private final int NO_USED_SOURCE = 7;
  
  private float screenScale = 3 / 4;
  private TextView liveback;
  private TextView title;
  private RelativeLayout liveRel;
  private ImageView livePlayer;
  private TextView tvTime;
  private VideoBean videoBean;
  private Context context;
  private SurfaceView mSurfaceView;
  private SurfaceHolder mSurfaceHolder;
  private PowerManager.WakeLock mWakeLock = null;
  private Timer mTimer=new Timer();
  private boolean isExitLivePlay = false;
  private String currentPos;
  
  /******************************************************* 
   * 通过定时器和Handler来更新进度条 
   ******************************************************/  
  TimerTask mTimerTask = new TimerTask() {  
      @Override  
      public void run() {  
          if(mPlayer==null)  
              return;  
          if (mPlayer.isPlaying() && seekBar.isPressed() == false) {  
              handler.sendEmptyMessage(0);  
          }  
      }  
  };  
    
  
  Handler handler = new Handler(){
    public void handleMessage(android.os.Message msg) {
      switch (msg.what) {
        case 0:
        {
          int position = mPlayer.getCurrentPosition();  
          int duration = mPlayer.getDuration();  
          
          //Log.e("TAG", "duration=====>" + duration);
          int allTime = duration /1000;
          
          if (position/1000 < 60) {
              if(position/1000 < 10){
            	  currentPos = "0" + position/1000;
              } else {
            	  currentPos = "" + position/1000;
              }
            } else {
              currentPos = (position/1000/60) + ":" + (position/1000 % 60);
            }
            
            String min = "";
            if(allTime/60 < 10){
            	min = "0"+allTime/60;
            } else {
            	min = "" + allTime/60;
            }
            String sec = "";
            if(allTime%60 < 10){
            	sec = "0"+allTime%60;
            } else {
            	sec = "" + allTime%60;
            }
            
            tvTime.setText(currentPos + "/" + min + ":" + sec);
          
          if (duration > 0) {  
            long pos = seekBar.getMax() * position / duration;  
            seekBar.setProgress((int) pos);  
          }  
          
        }
          break;
          
        case SHOW_RELATIVE:
          showRelativeLayout();
          break;

        case HIDE_RELATIVE:
          hideRelativeLayout();
          break;

        case SHOW_PROGRESS:
          ((ProgressBar) findViewById(R.id.program_live_probar)).setVisibility(View.VISIBLE);
          break;

        case HIDE_PROGRESS:
          ((ProgressBar) findViewById(R.id.program_live_probar)).setVisibility(View.INVISIBLE);
          break;

        case PLAY_SNED_IR_CODE_KEY_TONE:
          // new Thread(new Runnable() {
          // @Override
          // public void run() {
          // playSendIrCodeKeyTone();
          // }
          // }).start();
          break;

        case TURN_NEXT_SOURCE:
          //obtainVideFromUrl();
          break;

        case PLAY_VIDEO:
          playLiveRadio();
          break;

        case NO_USED_SOURCE:
          errorPlayDismiss(getString(R.string.program_no_live_source));
          break;


        default:
          break;
      }
      
    };
    
  };
  
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    
    //屏幕
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
      WindowManager.LayoutParams.FLAG_FULLSCREEN);   
    
    //設置不鎖屏
    PowerManager pManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "XYTEST");
    mWakeLock.acquire();
    
    setContentView(R.layout.video_play);
    
    this.context = this;
    
    videoBean = (VideoBean) getIntent().getSerializableExtra("video");
    findViews();
    initValues();
    setListeners();
    mTimer.schedule(mTimerTask,0, 1000);
    
    
  }
  
  
  @Override
  protected void onResume() {
    
    if (mWakeLock == null) {
      PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
      mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "XYTEST");
      mWakeLock.acquire();
    }

    if (null != mPlayer && !mPlayer.isPlaying()) {
      mPlayer.start();
    }
    createMediaplayer();
    super.onResume();
  }
  
  
  private void setListeners() {
    
    //
    mSurfaceView.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (View.INVISIBLE == liveRel.getVisibility()) {
          handler.sendEmptyMessage(SHOW_RELATIVE);
        } else {
          handler.sendEmptyMessage(HIDE_RELATIVE);
        }
      }
    });
    
    //返回
    liveback.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        finish();
      }
    });

//    liveFullScreen.setOnClickListener(new View.OnClickListener() {
//      @Override
//      public void onClick(View v) {
//        // setScreen();
//        changeSurfaceViewSize();
//      }
//    });
    
    livePlayer.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        playOrPause();
      }
    });
    
  }

  private void initValues() {
    
    //标题
    title.setText(videoBean.getTitle());
    
    mSurfaceHolder = mSurfaceView.getHolder();
    mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    mSurfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
    mSurfaceHolder.addCallback(new Callback() {
      @Override
      public void surfaceDestroyed(SurfaceHolder paramSurfaceHolder) {
      }
      @Override
      public void surfaceCreated(SurfaceHolder paramSurfaceHolder) {
        handler.sendEmptyMessage(PLAY_VIDEO);
      }
      @Override
      public void surfaceChanged(SurfaceHolder paramSurfaceHolder, int paramInt1, int paramInt2,
          int paramInt3) {
      }
    });


    
  }

  private void findViews() {
    liveback = (TextView) findViewById(R.id.program_live_back);
    title = (TextView) findViewById(R.id.program_live_channel_name);
    liveRel = (RelativeLayout) findViewById(R.id.program_live_rel);
    livePlayer = (ImageView) findViewById(R.id.program_live_player);
    tvTime = (TextView) findViewById(R.id.tv_time);
    
    mSurfaceView = (SurfaceView) findViewById(R.id.program_live_play_surface);
    seekBar = (SeekBar) findViewById(R.id.program_live_seekbar);
    
  }
  
  boolean videoIsPlay;
  private MediaPlayer mPlayer;
  private void playOrPause() {
    if (videoIsPlay) {
      if (null != mPlayer && mPlayer.isPlaying()) {
        log.d("playOrPause mPlayer1.pause() ");
        mPlayer.pause();
        videoIsPlay = false;
        livePlayer.setBackgroundResource(R.drawable.play);
      }
    } else {
      if (null != mPlayer) {
        log.d("playOrPause mPlayer1.start() ");
        mPlayer.start();
        videoIsPlay = true;
        livePlayer.setBackgroundResource(R.drawable.pause);
        log.i("times:" + mPlayer.getDuration());
      }
    }
  }
  
  private void hideRelativeLayout() {
    liveRel.setVisibility(View.INVISIBLE);
  }

  private void showRelativeLayout() {
    liveRel.setVisibility(View.VISIBLE);
  }
  
  //創建播放器
  private void createMediaplayer() {
    if (mPlayer == null) {
      Log.d("TAG","new a mediaplayer");
      mPlayer = new MediaPlayer();
      mPlayer.setOnBufferingUpdateListener(bufferListener);
      mPlayer.setOnCompletionListener(completionListener);
      mPlayer.setOnErrorListener(errorListener);
      mPlayer.setOnInfoListener(infoListener);
      mPlayer.setOnPreparedListener(prepareListener);
      mPlayer.setOnVideoSizeChangedListener(sizeChangedListener);
    }
  }
  
  
  private void errorPlayDismiss(String message) {
    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
  }
  
  MediaPlayer.OnBufferingUpdateListener bufferListener = new OnBufferingUpdateListener() {
    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
      
      seekBar.setSecondaryProgress(percent);  
      int currentProgress=seekBar.getMax()*mPlayer.getCurrentPosition()/mPlayer.getDuration();  
      
      Log.e(currentProgress+"% play", percent + "% buffer");  
      
      //tvTime.setText("load:" + percent + tvTime.getText());
    }
  };

  MediaPlayer.OnErrorListener errorListener = new OnErrorListener() {
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
      if (100 == what) {
        log.d("mPlayer1 server had died ");
      }
      if (isExitLivePlay) {
        log.d("=======LivePlayActivity is finished=======");
        return false;
      }
   
      switch (extra) {
        case -1004:// MediaPlayer.MEDIA_ERROR_IO
          // Toast.makeText(context, "I/O error!please check out", Toast.LENGTH_LONG).show();
          errorPlayDismiss(getString(R.string.program_live_ioerror));
          break;
        case -1007:// MediaPlayer.MEDIA_ERROR_MALFORMED
          // Toast.makeText(context, "MEDIA_ERROR_MALFORMED error!please check out",
          // Toast.LENGTH_LONG).show();
          errorPlayDismiss(getString(R.string.program_live_malformederror));
          break;
        case -1010:// MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
          // Toast.makeText(context, "MEDIA_ERROR_UNSUPPORTED error!please check out",
          // Toast.LENGTH_LONG).show();
          errorPlayDismiss(getString(R.string.program_live_unsupportederror));
          break;
        case -110:// MediaPlayer.MEDIA_ERROR_TIMED_OUT:
          // Toast.makeText(context, "MEDIA_ERROR_TIMED_OUT error!please check out",
          // Toast.LENGTH_LONG).show();
          errorPlayDismiss(getString(R.string.program_live_timeouterror));
          break;

        default:
          // Toast.makeText(context, "unknown play error!please check out",
          // Toast.LENGTH_LONG).show();
          errorPlayDismiss(getString(R.string.program_live_unkownerror));
          break;
      }

      return false;
    }
  };

  MediaPlayer.OnPreparedListener prepareListener = new OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
      
      log.i("prepareListener times:" + mPlayer.getDuration()/1000);
      
      mPlayer.start();
      
      int totalTime = mPlayer.getDuration()/1000;
      
      tvTime.setText("/" + totalTime);
      
      
      if (mPlayer.isPlaying()) {
        log.d("prepareListener isPlaying");
        mPlayer.setScreenOnWhilePlaying(true);
      }
    }
  };

  MediaPlayer.OnCompletionListener completionListener = new OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
      log.i("MediaPlayer.OnCompletionListener===>onCompletion " + mp.getDuration() );
    }
  };

  MediaPlayer.OnVideoSizeChangedListener sizeChangedListener = new OnVideoSizeChangedListener() {
    @Override
    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
      log.d("onVideoSizeChanged width = " + width + " height = " + height);
      screenScale = (float) height / width;
      handler.sendEmptyMessage(HIDE_PROGRESS);
    }
  };

  MediaPlayer.OnInfoListener infoListener = new OnInfoListener() {
    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
      log.d("onInfo what = " + what + " extra = " + extra);
      return false;
    }
  };

  private SeekBar seekBar;
  
  
  private void playLiveRadio() {
    if (null == mPlayer) {
      log.d("mPlayer1 is null ");
      return;
    }

    // !mSurfaceHolder1.getSurface().isValid()
    log.d("mSurfaceHolder1.getSurface().isValid() : " + mSurfaceHolder.getSurface().isValid());
    if (null == mSurfaceHolder || null == mSurfaceHolder.getSurface()) {
      log.d("mSurfaceHolder1 is null or mSurfaceHolder1.getSurface() is null ");
      return;
    }

    if (null != mPlayer) {
      log.d("mPlayer1 reset ");
      mPlayer.reset();
    }

    if (isExitLivePlay) {
      log.d("isExitLivePlay : " + isExitLivePlay);
      return;
    }

    mPlayer.setDisplay(mSurfaceHolder);

    try {
      log.d("--------------> strVideoURL : " + videoBean.getUrlFlv());
      mPlayer.setDataSource(context, Uri.parse(videoBean.getUrlFlv()));
      mPlayer.prepareAsync();
      log.i("times:---->" + mPlayer.getDuration());
      
      //handler.sendEmptyMessage(HIDE_RELATIVE);
      
    } catch (IllegalArgumentException e) {
      log.e("ex : " + e.toString());
    } catch (IOException e) {
      log.e("ex : " + e.toString());
    }
  }

  @Override
  protected void onPause() {
    log.i("************* onPause");
    if (null != mPlayer && mPlayer.isPlaying()) {
      log.d("playOrPause mPlayer1.pause() ");
      mPlayer.pause();
    }
    super.onPause();
  }

  @Override
  protected void onStop() {
    log.i("************* onStop");
    if (mWakeLock != null) {
      mWakeLock.release();
      mWakeLock = null;
    }

    if (null != mPlayer) {
      mPlayer.stop();
      // mPlayer1.reset();
      mPlayer.release();
      mPlayer = null;
    }
    super.onStop();
  }

  @Override
  protected void onDestroy() {
    log.i("************* onDestroy");
    // RunningActivityMng.instance().removeActivity(ProgramLivePlayActivity.this);
    try {
      if (mPlayer != null) {
        mPlayer.stop();
        // mMediaPlayer.reset();
        mPlayer.release();
        mPlayer = null;
      }
    } catch (Exception ex) {
      log.e("ex: " + ex.toString());
    }

    releaseMemory();
    super.onDestroy();
  }
  
  private void releaseMemory() {
 
    if (mWakeLock != null) {
      mWakeLock.release();
      mWakeLock = null;
    }
    try {
      if (null != mPlayer) {
        log.d("============mPlayer1 reset==========");
        mPlayer.stop();
        // mPlayer1.reset();
        mPlayer.release();
        mPlayer = null;
      }
    } catch (Exception e) {
      log.d("ex : " + e.toString());
    }
    if (null != mSurfaceView) {
      log.d("mSurfaceView1 is not null , release mSurfaceView1");
      mSurfaceView = null;
    }
    if (null != mSurfaceHolder) {
      log.d("mSurfaceHolder1 is not null , release mSurfaceHolder1");
      mSurfaceHolder = null;
    }
  }
  
  
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (KeyEvent.KEYCODE_BACK == keyCode) {
      isExitLivePlay = true;
      finish();
    }
    return super.onKeyDown(keyCode, event);
  }

 
  
  

}
